import os
import json
import asyncio
import websockets
from aiohttp import web
from client.web_client import WebClient

# 全局存储活跃的Web客户端
active_web_clients = {}

class WebInterfaceHandler:
    """Web界面处理器"""

    def __init__(self):
        self.web_client = None
        self.ws_connections = set()

    async def handle_index(self, request):
        """处理主页请求"""
        # 返回聊天室HTML页面
        html_content = '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OpenIM Web 客户端</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            width: 90%;
            max-width: 1200px;
            height: 90vh;
            background: white;
            border-radius: 10px;
            box-shadow: 0 15px 30px rgba(0,0,0,0.2);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .header {
            background: #4a5568;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 1.5rem;
            font-weight: 500;
        }

        .status {
            font-size: 0.9rem;
            opacity: 0.9;
        }

        .chat-container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .sidebar {
            width: 250px;
            background: #f7fafc;
            border-right: 1px solid #e2e8f0;
            padding: 20px;
            overflow-y: auto;
        }

        .sidebar h3 {
            margin-bottom: 15px;
            color: #4a5568;
            font-size: 1.1rem;
        }

        .user-list {
            list-style: none;
        }

        .user-list li {
            padding: 8px 12px;
            border-radius: 5px;
            margin-bottom: 5px;
            background: #edf2f7;
            color: #4a5568;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #ffffff;
        }

        .message {
            margin-bottom: 15px;
            padding: 10px 15px;
            border-radius: 8px;
            max-width: 70%;
            word-wrap: break-word;
        }

        .received {
            background: #edf2f7;
            align-self: flex-start;
            border-top-left-radius: 0;
        }

        .sent {
            background: #4299e1;
            color: white;
            align-self: flex-end;
            border-top-right-radius: 0;
            margin-left: auto;
        }

        .system {
            background: #fff5f5;
            color: #c53030;
            text-align: center;
            max-width: 100%;
            font-style: italic;
        }

        .message-header {
            font-weight: bold;
            margin-bottom: 5px;
            font-size: 0.9rem;
        }

        .message-time {
            font-size: 0.75rem;
            opacity: 0.8;
            margin-top: 5px;
        }

        .input-area {
            padding: 15px;
            background: #f7fafc;
            border-top: 1px solid #e2e8f0;
            display: flex;
        }

        .message-input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #e2e8f0;
            border-radius: 20px;
            outline: none;
            font-size: 1rem;
            resize: none;
            max-height: 150px;
        }

        .send-button {
            margin-left: 10px;
            padding: 12px 20px;
            background: #4299e1;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-weight: 500;
            transition: background 0.2s;
        }

        .send-button:hover {
            background: #3182ce;
        }

        .login-form {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 400px;
        }

        .login-form h2 {
            text-align: center;
            margin-bottom: 25px;
            color: #4a5568;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #4a5568;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #e2e8f0;
            border-radius: 5px;
            font-size: 1rem;
            outline: none;
            transition: border-color 0.2s;
        }

        .form-group input:focus {
            border-color: #4299e1;
        }

        .login-button {
            width: 100%;
            padding: 12px;
            background: #4299e1;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s;
        }

        .login-button:hover {
            background: #3182ce;
        }

        .hidden {
            display: none;
        }

        .error-message {
            color: #e53e3e;
            background: #fed7d7;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            text-align: center;
        }

        @media (max-width: 768px) {
            .container {
                width: 100%;
                height: 100vh;
                border-radius: 0;
            }

            .sidebar {
                width: 200px;
            }
        }

        @media (max-width: 480px) {
            .chat-container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                border-right: none;
                border-bottom: 1px solid #e2e8f0;
                height: 150px;
            }
        }
    </style>
</head>
<body>
    <div class="login-form" id="loginForm">
        <h2>OpenIM Web 客户端</h2>
        <div id="errorMessage" class="error-message hidden"></div>
        <div class="form-group">
            <label for="serverAddress">服务器地址</label>
            <input type="text" id="serverAddress" value="ws://localhost:18229" placeholder="例如: ws://localhost:18229">
        </div>
        <div class="form-group">
            <label for="userId">用户ID</label>
            <input type="text" id="userId" placeholder="输入您的用户ID">
        </div>
        <div class="form-group">
            <label for="roomId">房间ID</label>
            <input type="text" id="roomId" value="default" placeholder="输入房间ID">
        </div>
        <button class="login-button" onclick="connect()">连接</button>
    </div>

    <div class="container hidden" id="chatContainer">
        <div class="header">
            <h1>OpenIM 聊天室</h1>
            <div class="status" id="connectionStatus">连接中...</div>
        </div>

        <div class="chat-container">
            <div class="sidebar">
                <h3>在线用户</h3>
                <ul class="user-list" id="userList">
                    <!-- 用户列表将在这里动态添加 -->
                </ul>
            </div>

            <div class="main-content">
                <div class="messages" id="messages">
                    <!-- 消息将在这里动态添加 -->
                </div>

                <div class="input-area">
                    <textarea class="message-input" id="messageInput" placeholder="输入消息..." rows="1"></textarea>
                    <button class="send-button" onclick="sendMessage()">发送</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let webSocket = null;
        let userId = '';
        let isConnected = false;

        // 自动调整文本框高度
        document.getElementById('messageInput').addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });

        // 处理回车发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 连接到聊天服务器
        function connect() {
            const serverAddress = document.getElementById('serverAddress').value.trim();
            userId = document.getElementById('userId').value.trim();
            const roomId = document.getElementById('roomId').value.trim();

            if (!serverAddress || !userId) {
                showError('请填写服务器地址和用户ID');
                return;
            }

            try {
                // 创建WebSocket连接
                webSocket = new WebSocket(serverAddress);

                webSocket.onopen = function(event) {
                    console.log('WebSocket连接已建立');

                    // 发送注册信息
                    const registerData = {
                        type: 'register',
                        user_id: userId,
                        room_id: roomId
                    };

                    webSocket.send(JSON.stringify(registerData));
                    isConnected = true;

                    // 显示聊天界面
                    document.getElementById('loginForm').classList.add('hidden');
                    document.getElementById('chatContainer').classList.remove('hidden');
                    document.getElementById('connectionStatus').textContent = '已连接';
                    document.getElementById('connectionStatus').style.color = '#48bb78';
                };

                webSocket.onmessage = function(event) {
                    const messageData = JSON.parse(event.data);
                    handleMessage(messageData);
                };

                webSocket.onclose = function(event) {
                    console.log('WebSocket连接已关闭');
                    isConnected = false;
                    document.getElementById('connectionStatus').textContent = '连接已断开';
                    document.getElementById('connectionStatus').style.color = '#e53e3e';
                };

                webSocket.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                    showError('连接服务器时发生错误');
                };

            } catch (error) {
                console.error('连接错误:', error);
                showError('无法连接到服务器');
            }
        }

        // 处理接收到的消息
        function handleMessage(messageData) {
            switch (messageData.type) {
                case 'text':
                    displayTextMessage(messageData);
                    break;
                case 'system':
                    displaySystemMessage(messageData);
                    break;
                case 'user_list':
                    updateUserList(messageData.users);
                    break;
                case 'error':
                    displayErrorMessage(messageData);
                    break;
                default:
                    console.log('未知消息类型:', messageData.type);
            }
        }

        // 显示文本消息
        function displayTextMessage(messageData) {
            const messagesContainer = document.getElementById('messages');
            const messageDiv = document.createElement('div');

            const isOwnMessage = messageData.sender === userId;
            messageDiv.className = `message ${isOwnMessage ? 'sent' : 'received'}`;

            messageDiv.innerHTML = `
                <div class="message-header">${messageData.sender}</div>
                <div>${escapeHtml(messageData.message)}</div>
                <div class="message-time">${messageData.timestamp}</div>
            `;

            messagesContainer.appendChild(messageDiv);
            scrollToBottom();
        }

        // 显示系统消息
        function displaySystemMessage(messageData) {
            const messagesContainer = document.getElementById('messages');
            const messageDiv = document.createElement('div');

            messageDiv.className = 'message system';
            messageDiv.innerHTML = `
                <div>${escapeHtml(messageData.message)}</div>
                <div class="message-time">${messageData.timestamp}</div>
            `;

            messagesContainer.appendChild(messageDiv);
            scrollToBottom();
        }

        // 显示错误消息
        function displayErrorMessage(messageData) {
            const messagesContainer = document.getElementById('messages');
            const messageDiv = document.createElement('div');

            messageDiv.className = 'message system';
            messageDiv.innerHTML = `
                <div>错误: ${escapeHtml(messageData.message)}</div>
                <div class="message-time">${messageData.timestamp}</div>
            `;

            messagesContainer.appendChild(messageDiv);
            scrollToBottom();
        }

        // 更新用户列表
        function updateUserList(users) {
            const userListElement = document.getElementById('userList');
            userListElement.innerHTML = '';

            users.forEach(user => {
                const userItem = document.createElement('li');
                userItem.textContent = user;
                userListElement.appendChild(userItem);
            });
        }

        // 发送消息
        function sendMessage() {
            if (!isConnected || !webSocket) {
                showError('未连接到服务器');
                return;
            }

            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();

            if (message) {
                // 创建本地消息对象
                const localMessageData = {
                    type: 'text',
                    sender: userId,  // 使用当前用户ID
                    message: message,
                    timestamp: new Date().toLocaleTimeString()
                };

                // 先在本地显示消息
                displayTextMessage(localMessageData);

                // 然后发送到服务器
                const messageData = {
                    type: 'text',
                    message: message
                };

                webSocket.send(JSON.stringify(messageData));
                messageInput.value = '';
                messageInput.style.height = 'auto';
            }
        }

        // 显示错误信息
        function showError(message) {
            const errorElement = document.getElementById('errorMessage');
            errorElement.textContent = message;
            errorElement.classList.remove('hidden');

            // 3秒后自动隐藏错误信息
            setTimeout(() => {
                errorElement.classList.add('hidden');
            }, 3000);
        }

        // 滚动到底部
        function scrollToBottom() {
            const messagesContainer = document.getElementById('messages');
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 转义HTML字符
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };

            return text.replace(/[&<>"']/g, function(m) { return map[m]; });
        }
    </script>
</body>
</html>
        '''
        return web.Response(text=html_content, content_type='text/html')

# 创建应用路由
def setup_routes(app):
    handler = WebInterfaceHandler()
    app.router.add_get('/', handler.handle_index)
    # 可以添加更多路由

# 创建AIOHTTP应用
def create_app():
    app = web.Application()
    setup_routes(app)
    return app

# 启动Web服务器
def start_web_server(host='localhost', port=8080):
    app = create_app()
    web.run_app(app, host=host, port=port)

if __name__ == '__main__':
    print("OpenIM Web 服务器启动在 http://localhost:8080")
    start_web_server()
